<?php
namespace app\wechat\pay;
/**
 * 微信移动端服务
 */
class WechatMobilePay extends \app\base\service\BaseService {

    private $rsa = '';


    private function payConfig($notifyUrl = '') {
        $config = target('member/PayConfig')->getConfig('wechat_mobile');
        if (empty($config['mch_id']) || empty($config['md5_key'])) {
            return $this->error('请先配置支付接口信息!');
        }
        $wechatConfig = target('wechat/WechatConfig')->getConfig();
        if(empty($wechatConfig['appid'])) {
            return $this->error('公众号ID未设置!');
        }
        $notifyUrl = DOMAIN . $notifyUrl;
        return [
            'app_id' => $wechatConfig['appid'],
            'mch_id' => $config['mch_id'],
            'md5_key' => $config['md5_key'],
            'notify_url' => $notifyUrl,
            'time_expire'	=> 5,
        ];
    }

    public function getUrl($data, $returnUrl) {
        if (empty($data)) {
            return $this->error('订单数据未提交!');
        }

        if(!$this->isWechat()) {
            return $this->error('暂不支持微信外部访问！');
        }

        $returnUrl = DOMAIN . $returnUrl;
        $notifyUrl = url('api/wechat/WechatMobile/index');
        $config = $this->payConfig($notifyUrl);

        $ip = \dux\lib\Client::getUserIp();
        $oauthInfo = target('member/MemberConnect')->getWhereInfo([
            'user_id' => $data['user_id'],
            'type' => 'wechat'
        ]);


        if(empty($oauthInfo)) {
             return $this->error('微信用户尚未注册!');
        }

        $payData = [
            'order_no' => $data['order_no'],
            'amount' => $data['money'] ? price_format($data['money']) : 0,
            'client_ip' => ($ip == '::1') ?  '127.0.0.1' : $ip,
            'subject' => str_len($data['title'], 125),
            'body' => $data['body'] ? $data['body'] : $data['title'],
            'extra_param' => $data['app'],
            'openid' => $oauthInfo['open_id'],
        ];

        if (empty($payData['order_no'])) {
            return $this->error('订单号不能为空!');
        }
        if ($payData['amount'] <= 0) {
            return $this->error('支付金额不正确!');
        }
        if (empty($payData['subject']) || empty($payData['body'])) {
            return $this->error('支付信息描述不正确!');
        }
        if (empty($payData['extra_param'])) {
            return $this->error('订单应用名不正确!');
        }
        try {
            $charge = new \Payment\ChargeContext();
            $type = \Payment\Config::WX_CHANNEL_PUB;
            $charge->initCharge($type, $config);
            $json = $charge->charge($payData);
            $params = json_decode($json, true);
            $params['url'] = $returnUrl;
            $url = url('mobile/wechat/Pay/index') . '?' . http_build_query($params);
            return $this->success($url);
        } catch (\Payment\Common\PayException $e) {
            return $this->error($e->errorMessage());
        }
    }


    public function notifyPay($class) {
        if (!is_object($class)) {
            return $this->error('通知类错误!');
        }
        $config = $this->payConfig($notifyUrl = '');
        $notify = new \Payment\NotifyContext();
        $callback = $class;
        try {
            $notify->initNotify(\Payment\Config::WEIXIN, $config);
            return $this->success($notify->notify($callback));
        } catch (PayException $e) {
            return $this->error($e->errorMessage());
        }
    }

    protected function isWechat() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

}